package com.ytjj.qmyx.supplychain.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.api.ResultCode;
import com.ytjj.qmyx.supplychain.common.constants.CopyWriterConstant;
import com.ytjj.qmyx.supplychain.common.constants.SysConfigConstants;
import com.ytjj.qmyx.supplychain.common.enums.BrandStatusEnum;
import com.ytjj.qmyx.supplychain.common.enums.CompanyEnum;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.BankerInfoVO;
import com.ytjj.qmyx.supplychain.common.model.BankerLabelVO;
import com.ytjj.qmyx.supplychain.common.model.bill.request.BankerBillRequest;
import com.ytjj.qmyx.supplychain.common.model.bill.response.BankerBillResponse;
import com.ytjj.qmyx.supplychain.common.model.request.BankerRequest;
import com.ytjj.qmyx.supplychain.common.model.request.BankerUpdatePutOnRequest;
import com.ytjj.qmyx.supplychain.common.model.request.BrandUpdateNameRequest;
import com.ytjj.qmyx.supplychain.common.model.response.*;
import com.ytjj.qmyx.supplychain.common.utils.CopyWriterConfigUtil;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
@RefreshScope
public class BankerService {
    @Resource
    private BankerMapper bankerMapper;
    @Resource
    private BankerInfoMapper bankerInfoMapper;
    @Resource
    private BankerSiteMapper bankerSiteMapper;
    @Resource
    private SpecialBrandMapper specialBrandMapper;
    @Resource
    private BankerLabelMapper bankerLabelMapper;
    @Autowired
    private BankerBrandService bankerBrandService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private BankerSiteService bankerSiteService;
    @Autowired
    private BankerLabelService bankerLabelService;
    @Resource
    private BankerBankerLabelMapper bankerBankerLabelMapper;
    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;
    @Resource
    private BankerHolidayMsgMapper bankerHolidayMsgMapper;
    @Value(value = "${virtual.accounts:}")
    private String accounts;
    @Value(value = "${history-off:true}")
    private boolean historyOff;
    @Value(value = "${special-account:}")
    private String specialAccount;
    @Value(value = "${md5Configure.salt:}")
    private String salt;
    @Value(value = "${md5Configure.hashIterations:}")
    private Integer hashIterations;
    @Autowired
    private LinkErpService linkErpService;
    @Autowired
    private BillMapper billMapper;

    public CommonResult bankerLogin(String verCode, String verKey, String tel, String pwd) throws UnsupportedEncodingException {
        // 获取redis中的验证码
        String redisCode = redisService.get(verKey);
        // 判断验证码
        if (Strings.isEmpty(verCode) || !verCode.trim().toLowerCase().equals(redisCode)) {
            throw new ApiException("验证码不正确");
        }
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(tel, pwd);

        try {
            if (subject.isAuthenticated()) {
                subject.logout();
            }
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return CommonResult.failed("账号或密码错误！");
        } catch (AuthorizationException e) {
            e.printStackTrace();
            return CommonResult.failed("没有权限！");
        }
        // 供应商在管理后台下架后，提示账号异常
        int bankerStatus = queryBankerStatusByTel(tel);
        if (bankerStatus == 0) {
            return CommonResult.failed("您的账号存在异常，请与管理员联系！");
        }
        Session session = subject.getSession();
        String regex = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher isNum = pattern.matcher(pwd);
        Integer updateFlag = 1;
        if (!isNum.matches()) {
            updateFlag = 2;
        }

        Map<String,String> map = new HashMap<>();
        map.put("updateFlag",updateFlag.toString());
        map.put("session",session.getId().toString());
        map.put("message","登录成功！");
        return CommonResult.success(map);
    }

    public YxBanker queryBankerByTel(String tel) {
        Example example = new Example(YxBanker.class);
        example.createCriteria().andEqualTo("tel", tel);
        List<YxBanker> list = bankerMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    public Integer queryBankerStatusByTel(String tel) {
        YxBanker yxBanker = queryBankerByTel(tel);
        if (null == yxBanker) {
            return 0;
        }
        return yxBanker.getStatus();
    }

    public BankerResponse getUserInfo(String token) {
        BankerResponse bankerResponse = new BankerResponse();
        String sessionId = SecurityUtils.getSubject().getSession().getId().toString();
        String principal = getCurBankerTel();             // 获取当前用户的手机号
        String[] accountList = accounts.split(",");
        if (token.equals(sessionId)) {
            for (String account : accountList) {
                if (account.equals(principal)) {
                    YxBanker yxBanker = new YxBanker();
                    yxBanker.setTel(account);
                    yxBanker.setName("客服");
                    yxBanker.setStatus(1);
                    yxBanker.setLevel(3);
                    BeanUtils.copyProperties(yxBanker, bankerResponse);
                    return bankerResponse;
                }
            }
            YxBanker yxBanker = Optional.ofNullable(queryBankerByTel(principal))
                    .orElseThrow(() -> new ApiException("用户不存在"));
            BeanUtils.copyProperties(yxBanker, bankerResponse);
            Map<String, Object> checkBankerStatus = checkBankerStatus(principal);
            log.info("====checkBankerStatus==={}", checkBankerStatus);
            if (null != checkBankerStatus && !(boolean) checkBankerStatus.get("code")) {
                bankerResponse.setBankerAllStatus(false);
                bankerResponse.setNoData((Boolean) checkBankerStatus.get("noData"));
                bankerResponse.setBankerCheckMsg(checkBankerStatusMsg(principal));
            } else {
                bankerResponse.setBankerAllStatus(true);
            }
            LinkErpResponse linkErp = linkErpService.getByBankId(bankerResponse.getId());
            if(linkErp !=null && linkErp.getStatus() !=null ) {
                bankerResponse.setIsJoinErp(1 == linkErp.getStatus()? 1:0 );
            } else {
                bankerResponse.setIsJoinErp(0);
            }
            return bankerResponse;
        }
        return null;
    }

    private Map<String, Object> checkBankerStatus(String tel) {
        Map<String, Object> result = Maps.newHashMap();
        boolean checkResult = true;

        YxBanker yxBanker = queryBankerByTel(tel);
        if (null == yxBanker) {
            checkResult = false;
        }
        //用来判断是否是历史数据
        boolean isOldInfo = false;// true-历史数据  false-新数据
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date upLineTimeDate = sdf.parse("2021-04-13 00:00:00");
            if (yxBanker.getCreateTime().before(upLineTimeDate) && historyOff) {
                isOldInfo = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Example infoExample = new Example(YxBankerInfo.class);
        infoExample.createCriteria().andEqualTo("bankerId", yxBanker.getId());
        YxBankerInfo bankerInfo = bankerInfoMapper.selectOneByExample(infoExample);
        if (null != bankerInfo && 2 != bankerInfo.getStatus()) {
            checkResult = false;
        }
        Example siteExample = new Example(YxBankerSite.class);
        siteExample.createCriteria().andEqualTo("bankerId", yxBanker.getId());
        YxBankerSite bankerSite = bankerSiteMapper.selectOneByExample(siteExample);
        if (null != bankerSite && !BrandStatusEnum.PASS.getCode().equals(bankerSite.getCheckStatus())) {
            checkResult = false;
        }
        //如果是历史数据，则不需要判断品牌信息
        if (isOldInfo) {
            //如果是没有资质信息和店铺信息的
            if (!checkResult) {
                //判断是否是特殊账号
                checkResult = checkSpecialAccount(tel);
            }
            result.put("code", checkResult);
            result.put("noData", false);
            return result;
        }
        YxBankerBrand bankerBrand = bankerBrandService.selectByBankerIdAndFistTime(yxBanker.getId(), 1);
        if (null != bankerBrand && !BrandStatusEnum.PASS.getCode().equals(bankerBrand.getStatus())) {
            checkResult = false;
        }
        if (bankerBrand == null && bankerSite == null && bankerInfo == null) {
            checkResult = false;
            result.put("noData", true);
        } else {
            result.put("noData", false);
        }
        //如果是没有资质信息和店铺信息的
        if (!checkResult) {
            //判断是否是特殊账号
            checkResult = checkSpecialAccount(tel);
        }

        result.put("code", checkResult);
        return result;
    }

    private Map<String, Object> checkBankerStatusMsg(String tel) {
        Map<String, Object> result = null;
        boolean checkResult = true;

        YxBanker yxBanker = queryBankerByTel(tel);
        if (null == yxBanker) {
            checkResult = false;
        }
        //用来判断是否是历史数据
        boolean isOldInfo = false;// true-历史数据  false-新数据
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date upLineTimeDate = sdf.parse("2021-04-13 00:00:00");
            if (yxBanker.getCreateTime().before(upLineTimeDate) && historyOff) {
                isOldInfo = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Example infoExample = new Example(YxBankerInfo.class);
        infoExample.createCriteria().andEqualTo("bankerId", yxBanker.getId());
        YxBankerInfo bankerInfo = bankerInfoMapper.selectOneByExample(infoExample);
        if (null != bankerInfo && 3 == bankerInfo.getStatus()) {
            if (null == result) {
                result = Maps.newHashMap();
            }
            result.put("infoMsg", null == bankerInfo ? "" : bankerInfo.getRejectReason());
        }
        if (null != bankerInfo) {
            if (null == result) {
                result = Maps.newHashMap();
            }
            result.put("infoStatus", bankerInfo.getStatus() - 1);
        }
        Example siteExample = new Example(YxBankerSite.class);
        siteExample.createCriteria().andEqualTo("bankerId", yxBanker.getId());
        YxBankerSite bankerSite = bankerSiteMapper.selectOneByExample(siteExample);
        if (null != bankerSite && BrandStatusEnum.UN_PASS.getCode().equals(bankerSite.getCheckStatus())) {
            if (null == result) {
                result = Maps.newHashMap();
            }
            result.put("siteMsg", null == bankerSite ? "" : bankerSite.getCheckMsg());
        }
        if (null != bankerSite) {
            if (null == result) {
                result = Maps.newHashMap();
            }
            result.put("siteStatus", bankerSite.getCheckStatus());
        }
        //如果是历史数据，则不需要判断品牌信息
        if (isOldInfo) {
            return result;
        }
        YxBankerBrand bankerBrand = bankerBrandService.selectByBankerIdAndFistTime(yxBanker.getId(), 1);
        if (null != bankerBrand && BrandStatusEnum.UN_PASS.getCode().equals(bankerBrand.getStatus())) {
            if (null == result) {
                result = Maps.newHashMap();
            }
            result.put("brandMsg", "品牌：" + bankerBrand.getBrandName() + ",失败原因：" + bankerBrand.getCheckMsg());
        }
        if (null != bankerBrand) {
            if (null == result) {
                result = Maps.newHashMap();
            }
            result.put("brandStatus", bankerBrand.getStatus());
        }

        return result;
    }

    private boolean checkSpecialAccount(String tel) {
        log.info("===checkSpecialAccount==={}", tel);
        List<String> specialAccounts = Arrays.asList(specialAccount.split(","));
        if (specialAccounts.contains(tel)) {
            return true;
        }
        return false;
    }

    public void modifiedPassword(String tel, String pwd, String newPwd) {
        // 查询数据库是否存在该账户 -哈希+加盐+次数
        String resultPwd = new Md5Hash(pwd, salt, hashIterations).toString();
        Example example = new Example(YxBanker.class);
        Example.Criteria criteria = example.createCriteria();
        if(Strings.isEmpty(pwd)) {
            throw new ApiException("请输入原始密码！");
        }
        criteria.andEqualTo("tel", tel);
        criteria.andEqualTo("pwd", resultPwd);
        List<YxBanker> bankersList = Optional.ofNullable(bankerMapper.selectByExample(example))
                .orElseThrow(() -> new ApiException("用户不存在!"));
        String regex = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher isNum = pattern.matcher(newPwd);
        if (!isNum.matches()) {
            throw new ApiException("密码长度不少于8位且至少包含字母、数字！");
        }

        // 密码加密保存
        String password = new Md5Hash(newPwd, salt, hashIterations).toString();
        if(bankersList.size()<=0){
            throw new ApiException("原密码错误!");
        }
        YxBanker bankers = bankersList.get(0);
        bankers.setPwd(password);
        bankerMapper.updateByPrimaryKeySelective(bankers);
    }

    public CommonResult resetPwd(BrandUpdateNameRequest request) {
        YxBanker banker = bankerMapper.selectByPrimaryKey(request.getId());
        if (null == banker) {
            throw new ApiException("找不到对应的商家信息");
        }
        banker.setPwd("825c1bb1c258a575377b9af404a28776");
        Integer num = bankerMapper.updateByPrimaryKey(banker);
        if (num > 0) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    public YxBanker queryById(Integer id) {
        YxBanker banker = bankerMapper.selectByPrimaryKey(id);
        return banker;
    }

    public List<YxBanker> queryByIds(List<Integer> ids) {
        Example example = new Example(YxBanker.class);
        example.createCriteria().andIn("id", ids);
        List<YxBanker> bankers = bankerMapper.selectByExample(example);
        return bankers;
    }

    /**
     * 获取当前用户的信息
     *
     * @return
     */
    public YxBanker getUserInfo() {
        String principal = getCurBankerTel();
        YxBanker yxBanker = queryBankerByTel(principal);
        return yxBanker;
    }

    public String getCurBankerTel() {
        String tel = (String) SecurityUtils.getSubject().getPrincipal();
        if (null == tel) {
            throw new ApiException(ResultCode.UNAUTHORIZED);
        }
        return tel;
    }

    public YxBanker queryByNameLike(String name) {
        Example example = new Example(YxBanker.class);
        example.createCriteria().andLike("name", "%" + name + "%");
        YxBanker banker = bankerMapper.selectOneByExample(example);
        return banker;
    }

    public YxBanker addBanker(BankerRequest banker) {
        // 查看此供应商是否存在
        Example example = new Example(YxBanker.class);
        example.createCriteria().andEqualTo("name", banker.getName());
        int count = bankerMapper.selectCountByExample(example);
        if (count > 0) {
            throw new ApiException("该名称已存在！");
        }
        example.clear();
        example.createCriteria().andEqualTo("tel", banker.getTel());
        count = bankerMapper.selectCountByExample(example);
        if (count > 0) {
            throw new ApiException("手机号已存在");
        }
        String regex = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher isNum = pattern.matcher(banker.getPwd());
        if (!isNum.matches()) {
            throw new ApiException("密码长度不少于8位且至少包含字母、数字！");
        }
        //哈希+加盐+次数
        Md5Hash md5SaltIterateHash = new Md5Hash(banker.getPwd(), salt, hashIterations);
        banker.setPwd(md5SaltIterateHash.toString());
        banker.setCreateTime(new Date());
        banker.setStatus(SysConfigConstants.STATUS_1);
        banker.setAdminId(banker.getAdminId());
        banker.setAdminName(banker.getAdminName());

        YxBanker addBanker = new YxBanker();
        BeanUtils.copyProperties(banker, addBanker);
        bankerMapper.insertSelective(addBanker);

        //获取新增后的bankerId
        Integer bankerId = addBanker.getId();
        String specialIds = banker.getSpecialIds();
        if (StringUtils.isNotEmpty(specialIds)) {
            String[] specialIdStr = specialIds.split(",");
            for (String specialid : specialIdStr) {
                int id = Integer.valueOf(specialid);
                YxSpecialBrand specialBrand = new YxSpecialBrand();
                specialBrand.setSpecialId(id);
                specialBrand.setBankerId(bankerId);
                specialBrand.setStatus(1);
                specialBrand.setCreateTime(new Date());
                specialBrandMapper.insertSelective(specialBrand);
            }
        }
        return addBanker;
    }

    public CommonPage<BankerDataResponse> bankerList(BankerRequest bankerRequest) {
        AtomicBoolean canSee = new AtomicBoolean(false);

        if (null != bankerRequest.getIsEffective()){
            List<BankerContractNew> list = bankerContractNewMapper.selectByCountEndDate();
            //有有效合同的供应商id
            if (!CollectionUtils.isEmpty(list)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                List<Integer> collect = list
                        .stream()
                        .filter(item -> StringUtils.isNotBlank(item.getEndDate())
                                && getDate(sdf, item.getEndDate()).getTime() > System.currentTimeMillis())
                        .map(BankerContractNew::getBankerId)
                        .collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)){
                    return CommonPage.restPage(new ArrayList<>());
                }
                bankerRequest.setBankerIds(collect);
            }
        }

        PageHelper.startPage(bankerRequest.getPageNum(), bankerRequest.getPageSize());
        List<BankerDataResponse> bankerDataResponseList = bankerMapper.getBankerDataResponseList(bankerRequest);

        if(!CollectionUtils.isEmpty(bankerDataResponseList)) {
            List<Integer> bankerIds = bankerDataResponseList.stream().map(BankerDataResponse::getId).collect(Collectors.toList());
            log.info("====bankerIds==={}", JSONObject.toJSONString(bankerIds));
            Example example = new Example(YxBankerHolidayMsg.class);
            example.createCriteria().andIn("bankerId",bankerIds);
            //放假信息
            List<YxBankerHolidayMsg> yxBankerHolidayMsgs = bankerHolidayMsgMapper.selectByExample(example);
            //供应商主体信息
            List<BankerInfoVO> bankerInfoVOList = bankerInfoMapper.selectByBankerIds(bankerIds);
            //供应商标签信息
            List<YxBankerLabel> bankerLabels = bankerLabelMapper.selectByBankerIds(bankerIds);
            //供应商合同信息
            List<BankerContractNew> bankerContractNewList = bankerContractNewMapper.selectByBankerIds(bankerIds);
            for(BankerDataResponse bdr : bankerDataResponseList) {
                //供应商标签
                if (!CollectionUtils.isEmpty(bankerLabels)){
                    getBankerLabel(bdr,bankerLabels);
                }
                //放假信息
                if (!CollectionUtils.isEmpty(yxBankerHolidayMsgs)){
                    getBankerHolidayMsgs(yxBankerHolidayMsgs, bdr);
                }
                //供应商主体信息
                if (!CollectionUtils.isEmpty(bankerInfoVOList)){
                    getBankerInfoMsg(bdr,bankerInfoVOList);
                }
                //供应商合同信息
                if (!CollectionUtils.isEmpty(bankerContractNewList)){
                    getBankerContractMsg(bdr,bankerContractNewList);
                }
                //获取供应商其他信息
                getBankerOtherMsg(canSee, bdr);
            }
        }
        return CommonPage.restPage(bankerDataResponseList);
    }

    /**
     * 供应商合同信息
     * @param bdr
     * @param bankerContractNewList
     */
    private void getBankerContractMsg(BankerDataResponse bdr, List<BankerContractNew> bankerContractNewList) {
        List<BankerContractNew> contracts = bankerContractNewList.stream().filter(item -> bdr.getId().equals(item.getBankerId())).collect(Collectors.toList());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (!CollectionUtils.isEmpty(contracts)){
            bdr.setIsSign(1);
            Optional<BankerContractNew> first = contracts.stream().filter(item -> StringUtils.isNotBlank(item.getEndDate()) && getDate(sdf, item.getEndDate()).getTime() > System.currentTimeMillis()).findFirst();
            bdr.setIsEffective(first.isPresent() ? 1 : 0);
            List<Integer> companyIds = contracts.stream().map(BankerContractNew::getCompanyId).distinct().collect(Collectors.toList());
            List<String> commands = new ArrayList<>();
            if (companyIds.contains(CompanyEnum.QMYX.getCode())){
                commands.add(CompanyEnum.getMessageByCode(CompanyEnum.QMYX.getCode()));
            }
            if (companyIds.contains(CompanyEnum.TXG.getCode())){
                commands.add(CompanyEnum.getMessageByCode(CompanyEnum.TXG.getCode()));
            }
            if (companyIds.contains(CompanyEnum.HY.getCode())){
                commands.add(CompanyEnum.getMessageByCode(CompanyEnum.HY.getCode()));
            }
            bdr.setCompanys(commands);
        }else {
            bdr.setIsSign(0);
            bdr.setIsEffective(0);
            bdr.setCompanys(Collections.singletonList("无合同签订主体"));
        }
    }

    /**
     * //供应商主体信息
     * @param bdr
     * @param bankerInfoVOList
     */
    private void getBankerInfoMsg(BankerDataResponse bdr, List<BankerInfoVO> bankerInfoVOList) {
        Optional<BankerInfoVO> first = bankerInfoVOList.stream().filter(item -> bdr.getId().equals(item.getBankerId())).findFirst();
        first.ifPresent(bankerInfoVO -> bdr.setContractRemark(bankerInfoVO.getContractRemark()));
    }

    /**
     * 获取供应商其他信息
     * @param canSee
     * @param bdr
     */
    private void getBankerOtherMsg(AtomicBoolean canSee, BankerDataResponse bdr) {
        List<BankerResponse> specialBrand = bankerMapper.getSpecialBrand(bdr.getId());
        bdr.setBankerResponseList(specialBrand);
        if (null == bdr.getSaleNum() || bdr.getSaleNum().equals(0)) {
            bdr.setBackRatio(BigDecimal.ZERO);
        }else if (null == bdr.getBackNum() || bdr.getBackNum().equals(0)) {
            bdr.setBackRatio(BigDecimal.ZERO);
        }else {
            BigDecimal backRatio = new BigDecimal(bdr.getBackNum()).divide(new BigDecimal(bdr.getSaleNum()), 2, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            bdr.setBackRatio(backRatio);
        }
        if (!canSee.get()) {
            bdr.setSaleAmount(BigDecimal.ZERO);
            bdr.setSaleNum(0);
            bdr.setBackAmount(BigDecimal.ZERO);
            bdr.setBackRatio(BigDecimal.ZERO);
        }
    }

    /**
     * 供应商标签
     * @param bdr
     */
    private void getBankerLabel(BankerDataResponse bdr,List<YxBankerLabel> bankerLabelList) {
        List<YxBankerLabel> bankerLabels = bankerLabelList.stream().filter(item ->bdr.getId().equals(item.getBankerId())).collect(Collectors.toList());
        StringBuffer bankerLabelStr = new StringBuffer();
        List<Integer> bankerLabelIds = new ArrayList<>();
        if (!CollectionUtils.isEmpty(bankerLabels)){
            bankerLabels.forEach(bankerLabel -> {
                bankerLabelIds.add(bankerLabel.getBankerLabelId());
                bankerLabelStr.append(bankerLabel.getBankerLabelName()).append(", ");
            });
            List<BankerLabelVO> bankerLabelVOList = new ArrayList<>();
            bankerLabels.stream().forEach(item -> {
                BankerLabelVO vo = new BankerLabelVO();
                BeanUtils.copyProperties(item, vo);
                bankerLabelVOList.add(vo);
            });
            bdr.setBankerLabelList(bankerLabelVOList);
            bdr.setBankerLabelIds(bankerLabelIds);

        }
    }

    /**
     * 放假信息
     * @param yxBankerHolidayMsgs
     * @param bdr
     */
    private void getBankerHolidayMsgs(List<YxBankerHolidayMsg> yxBankerHolidayMsgs, BankerDataResponse bdr) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<YxBankerHolidayMsg> holidayMsgs = yxBankerHolidayMsgs.stream().filter(item -> bdr.getId().equals(item.getBankerId())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(holidayMsgs)){
            YxBankerHolidayMsg yxBankerHolidayMsg = holidayMsgs.get(0);
            String startTime = sdf.format(yxBankerHolidayMsg.getRecessStartTime());
            String endTime = sdf.format(yxBankerHolidayMsg.getRecessEndTime());
            bdr.setRecessTime(startTime + " 到 " + endTime);
            bdr.setDeliverTime(sdf.format(yxBankerHolidayMsg.getDeliverTime()));
            // 计算两个时间之间的差
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date recessStart = null;
            Date recessEnd = null;
            try {
                recessStart = sdf1.parse(startTime);
                recessEnd = sdf1.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (recessStart.getTime() > System.currentTimeMillis() || System.currentTimeMillis() > recessEnd.getTime()){
                bdr.setIsHoliday(0);
            }else {
                bdr.setIsHoliday(1);
            }
        }
    }

    public void updateStatusBanker(Integer id, Integer status, String msg) {
        YxBanker banker = new YxBanker();
        banker.setId(id);
        banker.setStatus((status));
        if (0 == status) {
            banker.setOffMsg(msg);
            banker.setOffTime(new Date());
        }else {
            banker.setOffMsg(null);
            banker.setOffTime(null);
        }
        bankerMapper.updateByPrimaryKeySelective(banker);

        if (0 == status) {
            //如果是停用供应商，则下架供应商下的：店铺、品牌和商品
            BankerUpdatePutOnRequest request = new BankerUpdatePutOnRequest();
            request.setBankerId(id);
            bankerSiteService.updateBankerSitePutOn(request);
//            offBankerSite(id);
//            offBankerProduct(id);
        }
    }

    /**
     * 查询所有助理
     * @return
     */
    public List<String> queryAssistantList() {
        Example example = new Example(YxBanker.class);
        example.createCriteria().andIsNotNull("assistant");
        example.selectProperties("assistant");
        List<YxBanker> list = bankerMapper.selectByExample(example);
        List<String> result = list.stream().map(YxBanker::getAssistant).collect(Collectors.toList());
        result = result.stream().distinct().collect(Collectors.toList());
        return result;
    }

    /**
     * 查询所有采购员
     * @return
     */
    public List<String> queryBuyerList() {
        Example example = new Example(YxBanker.class);
        example.createCriteria().andIsNotNull("buyer");
        example.selectProperties("buyer");
        List<YxBanker> list = bankerMapper.selectByExample(example);
        List<String> result = list.stream().map(YxBanker::getBuyer).collect(Collectors.toList());
        result = result.stream().distinct().collect(Collectors.toList());
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateBanker(BankerRequest banker) {
        YxBanker yxBanker1 = bankerMapper.selectByPrimaryKey(banker.getId());
        if (null != yxBanker1 && 2 == yxBanker1.getBillOrderType() && 2 != banker.getBillOrderType()){
            throw new ApiException("修改为“完成+7天”的取值规则后，取值规则就限制不能再改了");
        }
        banker.setUpdateTime(new Date());
        // 注销之前的数据
        Example example = new Example(YxSpecialBrand.class);
        example.createCriteria().andEqualTo("bankerId",banker.getId()).andEqualTo("status",1);
        List<YxSpecialBrand> specialBrandList = specialBrandMapper.selectByExample(example);
        if(specialBrandList.size() > 0) {
            specialBrandList.stream().forEach(item -> {
                item.setStatus(0);
                item.setUpdateTime(new Date());
                specialBrandMapper.updateByPrimaryKeySelective(item);
            });
        }
        String specialIds = banker.getSpecialIds();
        if (StringUtils.isNotEmpty(specialIds)) {
            String[] specialIdStr = specialIds.split(",");
            for (String specialid : specialIdStr) {
                int id = Integer.valueOf(specialid);
                YxSpecialBrand specialBrand = new YxSpecialBrand();
                specialBrand.setSpecialId(id);
                specialBrand.setBankerId(banker.getId());
                specialBrand.setStatus(1);
                specialBrand.setCreateTime(new Date());
                specialBrandMapper.insertSelective(specialBrand);
            }
        }
        //密码赋null,逆向工程时密码不做修改
        banker.setPwd(null);
        YxBanker yxBanker = new YxBanker();
        BeanUtils.copyProperties(banker,yxBanker);
        bankerMapper.updateByPrimaryKeySelective(yxBanker);
    }

    public List<Integer> getBankerIdByBankerName(String bankerName) {
        List<Integer> integer = bankerMapper.selectBankerIdByName(bankerName);
        return integer;
    }

    public CommonResult setHolidayMsg(YxBankerHolidayMsg request) {
        if (null == request.getRecessStartTime() || null == request.getRecessEndTime() || null == request.getDeliverTime()){
            throw new ApiException("请补充信息");
        }
        Example example = new Example(YxBankerHolidayMsg.class);
        example.createCriteria().andEqualTo("bankerId",request.getBankerId());
        example.setOrderByClause("id desc limit 1");
        YxBankerHolidayMsg yxBankerHolidayMsg = bankerHolidayMsgMapper.selectOneByExample(example);
        if (null != yxBankerHolidayMsg){
            yxBankerHolidayMsg.setRecessStartTime(request.getRecessStartTime());
            yxBankerHolidayMsg.setRecessEndTime(request.getRecessEndTime());
            yxBankerHolidayMsg.setDeliverTime(request.getDeliverTime());
            bankerHolidayMsgMapper.updateByPrimaryKeySelective(yxBankerHolidayMsg);
        }else {
            request.setCreateTime(new Date());
            bankerHolidayMsgMapper.insertSelective(request);
        }
        //查询供应商标签-春节打烊
        Example bankerLabelExample = new Example(YxBankerLabel.class);
        bankerLabelExample.createCriteria().andEqualTo("bankerLabelName","春节打烊");
        bankerLabelExample.setOrderByClause("create_time desc limit 1");
        YxBankerLabel yxBankerLabel = bankerLabelMapper.selectOneByExample(bankerLabelExample);
        if(null != yxBankerLabel){
            //查询该供应商是否存在这标签-春节不打烊
            Example bankerLabelBankerExample = new Example(YxBankerBankerLabel.class);
            bankerLabelBankerExample.createCriteria().andEqualTo("bankerLabelId",yxBankerLabel.getBankerLabelId()).andEqualTo("bankerId",request.getBankerId());
            Integer i = bankerBankerLabelMapper.selectCountByExample(bankerLabelBankerExample);
            //没有这个标签就添加
            if (i.compareTo(0) == 0){
                List<Integer> bankerIds = Arrays.asList(request.getBankerId());
                List<Integer> bankerLabelIds = Arrays.asList(yxBankerLabel.getBankerLabelId());
                bankerLabelService.addBankerLabel(bankerIds,bankerLabelIds,request.getAdminId());
            }
        }

        return CommonResult.success();
    }

    public CommonResult holidayMsg(Integer bankerId) {
        Example example = new Example(YxBankerHolidayMsg.class);
        example.createCriteria().andEqualTo("bankerId",bankerId);
        example.setOrderByClause("id desc limit 1");
        YxBankerHolidayMsg yxBankerHolidayMsg = bankerHolidayMsgMapper.selectOneByExample(example);
        if (null != yxBankerHolidayMsg){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            yxBankerHolidayMsg.setRecessStartTimeStr(sdf.format(yxBankerHolidayMsg.getRecessStartTime()));
            yxBankerHolidayMsg.setRecessEndTimeStr(sdf.format(yxBankerHolidayMsg.getRecessEndTime()));
            yxBankerHolidayMsg.setDeliverTimeStr(sdf.format(yxBankerHolidayMsg.getDeliverTime()));
            return CommonResult.success(yxBankerHolidayMsg);
        }
        return CommonResult.success(new ArrayList<>());
    }

    public Integer holidayMsgToMall(Integer bankerId) {
        Example example = new Example(YxBankerHolidayMsg.class);
        example.createCriteria().andEqualTo("bankerId",bankerId);
        example.setOrderByClause("id desc limit 1");
        YxBankerHolidayMsg yxBankerHolidayMsg = bankerHolidayMsgMapper.selectOneByExample(example);

        if (null != yxBankerHolidayMsg){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String startTime = sdf.format(yxBankerHolidayMsg.getRecessStartTime());
            String endTime = sdf.format(yxBankerHolidayMsg.getRecessEndTime());
            // 计算两个时间之间的差
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date recessStart = null;
            Date recessEnd = null;
            try {
                recessStart = sdf1.parse(startTime);
                recessEnd = sdf1.parse(endTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (recessStart.getTime() > System.currentTimeMillis() || System.currentTimeMillis() > recessEnd.getTime()){
                return 0;
            }else {
                return 1;
            }
        }else {
            return 0;
        }
    }

    public String getBankerIdsByBankerMsg(BankerRequest request) {
        return JSONObject.toJSONString(bankerMapper.selectByRequest(request));
    }

    public BankerBillResponse getBankerById(Integer bankerId){
        List<BankerBillResponse> list = bankerMapper.getBankerById(bankerId,null);
        if (!CollectionUtils.isEmpty(list)){
            return list.get(0);
        }
        return null;
    }

    public CommonResult bill(BankerBillRequest request) {
        PageHelper.startPage(request.getPageNum(),request.getPageSize());
        List<BankerBillResponse> list = bankerMapper.getBankerById(request.getBankerId(),request.getBankerName());
        if (!CollectionUtils.isEmpty(list)){
            list.forEach(item ->{
                Example example = new Example(YxBill.class);
                example.createCriteria().andEqualTo("bankerId",item.getBankerId());
                example.setOrderByClause("id desc limit 1");
                List<YxBill> yxBills = billMapper.selectByExample(example);
                if (!CollectionUtils.isEmpty(yxBills)){
                    YxBill yxBill = yxBills.get(0);
                    item.setBillStartTime(yxBill.getBillStartTime());
                    item.setBillEndTime(yxBill.getBillEndTime());
                    item.setSettlementAmount(yxBill.getPayableAmount());
                    item.setSettlementFreight(yxBill.getPayableFreight());
                }
            });
        }
        return CommonResult.success(CommonPage.restPage(list));
    }

    @Resource
    private BankerContractNewMapper bankerContractNewMapper;

    /**
     * 供应商合同新增-修改
     * @param request
     * @return
     */
    public CommonResult contractAddUpdate(BankerContractNew request) {
        if (null == request.getId()){
            //新增
            request.setCreateTime(new Date());
            bankerContractNewMapper.insertSelective(request);
        }else {
            //编辑
            BankerContractNew bankerContractNew = bankerContractNewMapper.selectByPrimaryKey(request.getId());
            Assert.isTrue(null != bankerContractNew,"合同不存在");
            bankerContractNewMapper.updateByPrimaryKeySelective(request);
        }
        return CommonResult.success();
    }

    /**
     * 供应商合同-列表
     * @param bankerId
     * @return
     */
    public CommonResult contractList(Integer bankerId) {
        List<BankerContractNewResponse> list = bankerContractNewMapper.selectByBankerId(bankerId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        list.stream().forEach(item ->{
            item.setCompany(CompanyEnum.getMessageByCode(item.getCompanyId()));
            if (StringUtils.isNotBlank(item.getEndDate())){
                Date date = getDate(sdf, item.getEndDate());
                assert date != null;
                item.setContractStatus(date.getTime() > System.currentTimeMillis() ? "有效" : "过期");
            }
        });
        return CommonResult.success(list);
    }

    private Date getDate(SimpleDateFormat sdf, String endDate) {
        endDate = endDate + " 23:59:59";
        Date date = null;
        try {
            date = sdf.parse(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 供应商合同-删除
     * @param id
     * @return
     */
    public CommonResult contractDel(Integer id) {
        int i = bankerContractNewMapper.deleteByPrimaryKey(id);
        return i > 0 ? CommonResult.success() :CommonResult.failed();
    }

    public CommonResult contractRemark(Integer bankerId, String contractRemark) {
        bankerInfoMapper.updateContractRemark(bankerId,contractRemark);
        return CommonResult.success();
    }


    public CommonResult getBankerInfoByName(String bankerName) {
        List<YxBanker> bankers = bankerMapper.getBankerByName(bankerName);
        return CommonResult.success(bankers);
    }
}
